const {
    BaseController
} = require('../../Base')

/**
 * 时间笔记基本操作
 */
class TimeNotesBase extends BaseController {
    constructor(dbName, valiFormEnum) {
        super()
        this.exDb = this.dbBase.collection(dbName);
        this.notFormKey = ['_id', '_openid']
        this.valiFormEnum = valiFormEnum
    }
    // 新增一条数据
    async addOne(data) {
        for (let key in this.valiFormEnum) {
            if (this.tools.validate.isEmpty(data[key]) && this.valiFormEnum[key]) {
                return this.resError(this.valiFormEnum[key])
            }
        }
        data._openid = this.getOpenid()
        data.createTime = Date.now()
        var result = await this.exDb.add({
            data
        })
        return this.resSuccess(result._id)
    }
    // 删除->id
    async removeById() {
        await this.exDb.where({
            _openid: this.getOpenid()
        }).remove()
        return this.resSuccess('删除成功')
    }
    // 更新->id
    async updateById(data) {
        var updateData = {}
        for (let key in data) {
            if (!this.notFormKey.includes(key)) {
                updateData[key] = data[key]
            }
        }
        var result = await this.exDb.where({
            _openid: this.getOpenid()
        }).update({
            data: updateData
        })
        return this.resSuccess(result.stats)
    }
    // 获取详情
    async getInfo() {
        var result = await this.exDb.where({
            _openid: this.getOpenid()
        }).get()
        return this.resSuccess(result.data)
    }
    // 获取分页列表
    async getList(data) {
        var skip = data.skip || 0
        var limit = data.limit || 20
        var result = await this.exDb.skip(skip).limit(limit).where({
            _openid: this.getOpenid()
        }).get()
        const countResult = await this.exDb.count()
        return this.resSuccess({
            list: result.data,
            total: countResult.total
        })
    }
    // 获取所有列表
    async getAllList() {
        const MAX_LIMIT = 100
        // 先取出集合记录总数
        const countResult = await this.exDb.count()
        const total = countResult.total
        if (total < 1) {
            return this.resSuccess([])
        }
        // 计算需分几次取
        const batchTimes = Math.ceil(total / 100)
        // 承载所有读操作的 promise 的数组
        const tasks = []
        for (let i = 0; i < batchTimes; i++) {
            const promise = this.exDb.skip(i * MAX_LIMIT).limit(MAX_LIMIT).where({
                _openid: this.getOpenid()
            }).get()
            tasks.push(promise)
        }
        // 等待所有
        var result = (await Promise.all(tasks)).reduce((acc, cur) => {
            return acc.data.concat(cur.data)
        })
        // 排序
        var sortResult = this.sortResult(result.data)
        return this.resSuccess(sortResult)
    }
    // 列表排序方法
    sortResult(list) {
        return list
    }
}

module.exports = TimeNotesBase